﻿using Dijiang.Errors;

namespace Dijiang.Values
{
    public class DExpression : DSequence
    {
        public DExpression() { }
        public DExpression(IEnumerable<DValue> cell) : base(cell) { }
        public DExpression(params DValue[] cell) : base(cell) { }

        public override DValue Copy()
        {
            return new DExpression(CopyCell());
        }

        public override DValue Eval(CmdEnv env)
        {
            for (int i = 0; i < items.Count; i++)
            {
                items[i] = items[i].Eval(env);

                if (items[i] is DError err) return err;
            }

            if (Count == 0) return new DError("trying to eval a empty expression");

            var fst = Pop();

            return fst is DFunction func ? func.Call(env, this) : new EvalNonFunctionError(fst);
        }
    }
}
